package com.df.happylearn.messages;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.df.happylearn.R;
import com.df.happylearn.articlecontent.ContentActivity;
import com.df.happylearn.model.MessageInfo;
import com.df.happylearn.utils.Constants;
import com.df.happylearn.view.DividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/5/25.
 */
public class MessagesFragment extends Fragment implements MessagesContract.View {

    private Context mContext;

    View no_message_ui;
    SwipeRefreshLayout mRefreshLayout;
    RecyclerView mRecyclerView;

    private LinearLayoutManager mLayoutManager;
    private List<MessageInfo> mMessageList = new ArrayList<>();
    private MessageListAdapter mAdapter;
    private List<Integer> mReadIds = new ArrayList<>();
    private MessagesContract.Presenter mPresenter;
    private boolean isLoading = false;

    public MessagesFragment() {

    }

    public static MessagesFragment newInstance() {
        return new MessagesFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_messages, null);
        mPresenter.getReadedIds();
        initView(view);
        initData();
        return view;
    }

    private void initView(View view) {
        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refreshLayout);
        mRefreshLayout.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.bg_actionbar));
        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(mContext);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL_LIST));
        mAdapter = new MessageListAdapter(mContext, mMessageList, mReadIds);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickLitener(onItemClickListener);
        mRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRecyclerView.addOnScrollListener(onScrollListener);

        no_message_ui = view.findViewById(R.id.no_message_ui);
        no_message_ui.setVisibility(View.GONE);
    }

    private void initData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefreshLayout.setRefreshing(true);
                mPresenter.start();
            }
        }, Constants.INIT_CONTENT_DELAYED);
    }

    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mPresenter.loadMessages(true);
        }
    };

    RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            setRefreshEnable(mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0);
            if (!isLoading && mAdapter != null && mLayoutManager.findLastVisibleItemPosition() == mAdapter.getItemCount() - 1) {
                isLoading = true;
                mPresenter.loadMessages(false);
            }
        }
    };

    MessageListAdapter.OnItemClickListener onItemClickListener = new MessageListAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            MessageInfo messageInfo = mMessageList.get(position);
            if (!"null".equals(messageInfo.mLinkNewsId)) {
                Intent intent = new Intent(mContext, ContentActivity.class);
                intent.putExtra("articleId", Integer.parseInt(messageInfo.mLinkNewsId));
                startActivityForResult(intent, Constants.MESSAGEACTIVITY_REQUEST_CODE);
            } else {
                AlertDialog alertDialog = new AlertDialog.Builder(mContext)
                        .setMessage(mMessageList.get(position).mContent)
                        .create();
                alertDialog.show();
                if (!mReadIds.contains(messageInfo.mId)) {
                    mPresenter.updateReadState(messageInfo.mId);
                }
            }
        }
    };

    private void setRefreshEnable(boolean isRefreshEnable) {
        mRefreshLayout.setEnabled(isRefreshEnable);
    }

    private void showNoNetworkView() {
        no_message_ui.setVisibility(View.VISIBLE);
        mRefreshLayout.setVisibility(View.GONE);
    }

    private void hideNoNetworkView() {
        no_message_ui.setVisibility(View.GONE);
        mRefreshLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void setPresenter(MessagesContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showMessages(List<MessageInfo> list, boolean isFirst) {
        if (isFirst) {
            mMessageList.clear();
        }
        mMessageList.addAll(list);
        mAdapter.notifyDataSetChanged();
        hideNoNetworkView();
        mRefreshLayout.setRefreshing(false);
        isLoading = false;
    }

    @Override
    public void showNoMessages() {
        showNoNetworkView();
    }

    @Override
    public void setReadIds(List<Integer> readIds) {
        mReadIds = readIds;
    }

    @Override
    public void addReadId(int id) {
        mReadIds.add(id);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constants.MESSAGEACTIVITY_REQUEST_CODE && resultCode == Constants.ACTICLEACTIVITY_RESULT_CODE && data != null) {
            int articleId = data.getIntExtra("article_id", -1);
            for (MessageInfo item : mMessageList) {
                if (item.mLinkNewsId.equals(String.valueOf(articleId))) {
                    if (!mReadIds.contains(item.mId)) {
                        mPresenter.updateReadState(item.mId);
                    }
                    break;
                }
            }
        }
    }
}
